using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
using System;

public class UIManagement
{
	public delegate void Confirm ();

	public delegate void Cancel ();
	
	//popup window
	public Confirm confirm;
	public Cancel cancel;
	public string popUpString;
	
	//TipsWindow
	public string tipsTitle;
	public string itemSpriteName;
	
	//Equip
	public string equipProfession;
	public string lvLimit;
	
	public string buttonLeftStr;
	public string buttonRightStr;
	
	
	public static UIManagement Instance ()
	{
		if (instance == null)
			instance = new UIManagement ();
		
		return instance;
	}
	
	public enum WindowAnchor
	{
		Right = 0,
		Left,
		Center,
	}
	
	static UIManagement instance;
	public string shallOpenWindowName;
	public GameObject uiParent;
	List<GameObject> windowList = new List<GameObject> ();
	Vector3 deltaDepth = Vector3.back * 10;
	Vector3 leftAnchor = new Vector3 (-716, 0, 0);
	Vector3 rightAnchor = new Vector3 (-252, 0, 0);
	Dictionary<byte,Vector3> anchorDic = new Dictionary<byte, Vector3> ();
	
	/// <summary>
	/// Opens a window,then set the window active or inactive;
	/// </summary>
	public GameObject OpenWindow (string windowName, bool isActive, WindowAnchor anchor)
	{
		foreach (GameObject go in windowList) {
			if (go.name.Equals (windowName))
				return go;
		}
		
		GameObject window = (GameObject)MonoBehaviour.Instantiate (Resources.Load (ResPath.UIPATH + windowName));
		
		if (uiParent == null) {
			uiParent = GameObject.Find (GameDefine.WINDOWPARENTTOREMOVE);
		}
		
		if (uiParent == null) {
			Debug.Log ("Can not find parent window --->" + GameDefine.WINDOWPARENTTOREMOVE);
			return null;
		}
		
		if (anchorDic == null || anchorDic.Count == 0) {
			float width = Camera.mainCamera.pixelWidth / 2;
			Vector3 widthVector = new Vector3 (width, 0, 0);
			anchorDic.Add ((byte)WindowAnchor.Center, Vector3.zero);
			anchorDic.Add ((byte)WindowAnchor.Left, leftAnchor + widthVector);
			anchorDic.Add ((byte)WindowAnchor.Right, rightAnchor + widthVector);
		}
		
		window.transform.parent = uiParent.transform;
		window.transform.localScale = Vector3.one;
		window.transform.localPosition = anchorDic [(byte)anchor];
		window.name = windowName;
		//window.tag = anchor.ToString();
		SetVisiable (window, isActive);
		
		windowList.Add (window);
		
		Rerange ();
		
		return window;
	}
	
	/// <summary>
	/// Opens a window,default set the window active
	/// <summary>
	public GameObject OpenWindow (string windowName, WindowAnchor anchor)
	{
		return OpenWindow (windowName, GameDefine.INVISIABLE, anchor);
	}
	
	/// <summary>
	/// Opens a window,default set the window center
	/// <summary>
	public GameObject OpenWindow (string windowName, bool isActive)
	{
		return OpenWindow (windowName, isActive, WindowAnchor.Center);
	}
	
	/// <summary>
	/// Closes the window.
	/// </summary>
	public void CloseWindow (GameObject closeTarget)
	{
		windowList.Remove (closeTarget);
		
		Rerange();
		
		MonoBehaviour.DestroyImmediate (closeTarget);
	}
	
	public void SetVisiable (GameObject windowTarget, bool visiable)
	{
		windowTarget.SetActive (visiable);
	}
	
	public void Rerange (GameObject upperWindow)
	{
		foreach (GameObject go in windowList) {
			if (go != upperWindow) {
				if (go.transform.localPosition.z < upperWindow.transform.localPosition.z) {
					Vector3 position1 = upperWindow.transform.localPosition;
					Vector3 position2 = go.transform.localPosition;
					
					position1.z = go.transform.localPosition.z;
					position2.z = upperWindow.transform.localPosition.z;
					
					upperWindow.transform.localPosition = position1;
					go.transform.localPosition = position2;
				}
			}
		}
	}
	
	void Rerange ()
	{
		for (int i = 0; i < windowList.Count; i++) {
			Vector3 pos = windowList [i].transform.localPosition;
			pos.z = i * deltaDepth.z;
			windowList [i].transform.localPosition = pos;
		}
	}
	
	/// <summary>
	/// Opens the pop up window without params;
	/// </summary>
	public void OpenPopUpWindow (string popupId, Confirm pConfirm, Cancel pCancel)
	{
		OpenPopUpWindow (popupId, pConfirm, pCancel, null);
	}
	
	/// <summary>
	/// Opens the pop up window with params;
	/// </summary>
	public void OpenPopUpWindow (string popupId, Confirm pConfirm, Cancel pCancel, params object[] valArr)
	{
		UIManagement.Instance ().OpenWindow ("Window_Popup", true);
		
		confirm = pConfirm;
		cancel = pCancel;
		
		if (valArr == null) {
			popUpString = BinaryReaderTool.getInstance ().getSwfLangStr (popupId);
		} else {
			popUpString = BinaryReaderTool.getInstance ().getSwfLangStrVar (popupId, valArr);
		}
		
		Debug.Log (popupId + "<-------->" + popUpString);
	}
	
	/// <summary>
	/// Opens the equip tips window.
	/// </summary>
	public void OpenEquipTipsWindow (Hashtable stringTable,Confirm pConfirm,Cancel pCancle,string leftStr,string rightStr)
	{
		GameObject tipWindow = UIManagement.Instance ().OpenWindow ("Window_EquipTips", true);
		
		if (CheckKey (stringTable, "TitleName")) {
			tipsTitle = stringTable["TitleName"].ToString();
		}
		
		if(CheckKey (stringTable, "SpriteName")){
			itemSpriteName = stringTable["SpriteName"].ToString();
		}
		
		if(CheckKey (stringTable, "EquipProfession")){
			string pre = BinaryReaderTool.getInstance().getSwfLangStr("String000052");
			string profession = BinaryReaderTool.getInstance().getSwfLangStr("Role" + int.Parse(stringTable["EquipProfession"].ToString()));
			equipProfession = pre + GameDefine.SPACE_ONE + profession;
		}
		
		if(CheckKey (stringTable, "LvLimit")){
			
			string pre = BinaryReaderTool.getInstance().getSwfLangStr("String000051");
			string suffix = BinaryReaderTool.getInstance().getSwfLangStr("String000062");
			
			lvLimit =pre + GameDefine.SPACE_ONE + stringTable["LvLimit"].ToString() + suffix;
		}
		
		Vector3 windowPosition = Vector3.zero;
		if(CheckKey (stringTable, "EquipPosition")){
			windowPosition = (Vector3)stringTable["EquipPosition"];
		}
		
		Camera camera = Camera.main;
		
		//Calculate the position of window
		if(camera != null){
			windowPosition = camera.WorldToScreenPoint(windowPosition);
			
			Transform bgFrame = tipWindow.transform.Find("WindowBackground");
			
			Vector3 scale = bgFrame.localScale;
			
			scale.x /= 2;
			scale.y /= 2;
			
			float width = camera.pixelWidth / 2;
			float height = camera.pixelHeight / 2;
			
			if(windowPosition.x < width && windowPosition.y < height){
				//Left-Bottom
				windowPosition.x += scale.x;
				windowPosition.y += scale.y;
			} else if(windowPosition.x >= width && windowPosition.y < height){
				//Right-Bottom
				windowPosition.x -= scale.x;
				windowPosition.y += scale.y;
			} else if(windowPosition.x < width && windowPosition.y >= height){
				//Left-Top
				windowPosition.x += scale.x;
				windowPosition.y -= (scale.y - 25);
			} else {
				//Right-Top
				windowPosition.x -= scale.x;
				windowPosition.y -= (scale.y - 25);
			}
			
			windowPosition = camera.ScreenToWorldPoint(windowPosition);
			
		} else {
			Debug.LogError("Please set a camera as mainCamera");
		}
		
		windowPosition.z = tipWindow.transform.position.z;
		
		tipWindow.transform.position = windowPosition;
		
		confirm = pConfirm;
		cancel = pCancle;
		
		buttonLeftStr = leftStr;
		buttonRightStr = rightStr;
	}
	
	public bool CheckWindowExits(string windowName){
		bool checkResult = false;
		
		for(int i = 0; i < windowList.Count;i++){
			if(windowList[i].name.Equals(windowName)){
				checkResult = true;
				break;
			}
		}
		
		return checkResult;
	}
	
	bool CheckKey (Hashtable table, string key)
	{
		return table.ContainsKey (key);
	}
	
	public GameObject GetWindow(string windowName){
		GameObject go = new GameObject();
		
		for(int i = 0; i < windowList.Count;i++){
			if(windowList[i].name.Equals(windowName)){
				go = windowList[i];
				break;
			}
		}
		
		return go;
	}
}
